package cn.cxyxj.code_auth_jwt_persistence_prod.impl;


import cn.cxyxj.code_auth_jwt_persistence_prod.entity.SysRole;
import cn.cxyxj.code_auth_jwt_persistence_prod.entity.SysUser;
import cn.cxyxj.code_auth_jwt_persistence_prod.entity.SysUserDetails;
import cn.cxyxj.code_auth_jwt_persistence_prod.mapper.SysMenuMapper;
import cn.cxyxj.code_auth_jwt_persistence_prod.mapper.SysRoleMapper;
import cn.cxyxj.code_auth_jwt_persistence_prod.mapper.SysUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author cxyxj
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        LambdaQueryWrapper<SysUser> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SysUser::getAccount, account);
        // 根据用户名查询用户
        SysUser sysUsers = sysUserMapper.selectOne(queryWrapper);
        if (Objects.isNull(sysUsers)) {
           throw new UsernameNotFoundException("User " + account + " does not exist");
        }
        // 获得用户角色名称
        List<SysRole> roles = sysRoleMapper.selectByUserId(sysUsers.getId());
        // 构建 SimpleGrantedAuthority 对象
        List<SimpleGrantedAuthority> authorities =
                roles.stream().map(SysRole::getRoleName).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        //根据角色获得接口url
        List<Integer> collect = roles.stream().map(SysRole::getId).collect(Collectors.toList());
        Set<String> urlSet = sysMenuMapper.seleteByRoleId(collect);
        return new SysUserDetails(sysUsers, authorities,urlSet);
    }

}
